package com.wxdc.nmgyt.nmgytwydc.dagger.module;

import android.text.TextUtils;
import android.util.Log;

import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.http.PersistentCookieStore;
import com.wxdc.nmgyt.nmgytwydc.http.api.RetrofitService;
import com.wxdc.nmgyt.nmgytwydc.utils.DeviceTool;
import com.wxdc.nmgyt.nmgytwydc.utils.SharedPreferenceUtil;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Interceptor;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/4/24.
 */
@Module
public class HttpModule {

    @Provides
    @Singleton
    RetrofitService provideRetrofitService(Retrofit retrofit){
        return retrofit.create(RetrofitService.class);
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(Retrofit.Builder builder,OkHttpClient client){
        return createRetrofit(builder,RetrofitService.HOST_BASE,client);
    }
    @Provides
    @Singleton
    Retrofit.Builder provideRetrofitBuilder(){
        return new Retrofit.Builder();
    }
    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(OkHttpClient.Builder okBuilder){
        //日志显示级别
        HttpLoggingInterceptor.Level level= HttpLoggingInterceptor.Level.BODY;
        //新建log拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("nmgyt","OkHttp====Message:"+message);
            }
        });
        loggingInterceptor.setLevel(level);
        //Header
        Interceptor headerInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                String token = SharedPreferenceUtil.getToken();
                Request.Builder requestBuilder = originalRequest.newBuilder()
                        .header("AppType", "TPOS")
                        .header("Content-Type", "application/json")
                        .header("Accept", "application/json")
                        .header("postDeviceTypes", "Android")
                        .header("clientType", "1")
                        .header("Authorization",
                                TextUtils.isEmpty(token)
                                        ? DeviceTool.getDeviceIdIMEI(MyApp.getInstance()
                                        .getApplicationContext())
                                        : token)
                        .method(originalRequest.method(), originalRequest.body());
                Request request = requestBuilder.build();
                return chain.proceed(request);
            }        };
        //OkHttp进行添加拦截器loggingInterceptor
        okBuilder.addInterceptor(loggingInterceptor);
        //设置头
        okBuilder.addInterceptor(headerInterceptor);
        //设置超时
        okBuilder.connectTimeout(20, TimeUnit.SECONDS);
        okBuilder.readTimeout(20, TimeUnit.SECONDS);
        okBuilder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        okBuilder.retryOnConnectionFailure(true);

        //Cookie持久化
        CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(MyApp.getInstance
                ().getApplicationContext()),
                CookiePolicy.ACCEPT_ALL);
        okBuilder.cookieJar(new JavaNetCookieJar(cookieHandler));
        return okBuilder.build();
    }
    @Provides
    @Singleton
    OkHttpClient.Builder provideOkHttpClientBuilder(){
        return new  OkHttpClient.Builder();
    }
    private Retrofit createRetrofit(Retrofit.Builder builder, String baseUrl, OkHttpClient client){
        Log.d("TAG", "createRetrofit:--------------------"+baseUrl);
        return builder
                .baseUrl(baseUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
}
